import React, { Component, useRef, createRef } from 'react';
import {
  Button,
  Modal,
  Select,
  Form,
  Tag,
  Row,
  Col,
  Input,
  DatePicker,
  Radio,
  Tabs,
  Tree,
  message,
} from 'antd';
const { TabPane } = Tabs;
const { TextArea } = Input;
const { TreeNode } = Tree;
import moment from 'moment';
import ReportCard from '@/components/ReportCard';

import style from './index.css';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import EndoscopetDetailTable from './EndoscopetDetailTable';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
@Form.create()
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.endoscopetDetailTable = createRef();
    this.state = {
      visible: false,
      hpjcjgDisabled: false,
      activeKey: '1',
      treeListData: [],
      form: {},
      tag1: [],
      tag2: [],
      tag3: [],
      tag4: [],
      tag5: [],
      njzd: { '1': [], '2': [], '3': [], '4': [], '5': [] },
      showTags: [],
      getByIdOver: false, // getById 是否请求结束
      acheData: [],
      dyeData: [],
      hpData: [],
      isHjData: [],
      hpjcjgData: [],
      reportFilePath: undefined,
      njzd_content: undefined,
    };
  }

  showModal = () => {
    this.findAllDictName();

    // this.findById()
    this.setState({
      visible: true,
    });
  };
  // 配合 initDetailData 筛选出多余数据 并在保存前至空
  computedShowDetial = () => {
    const { njzd } = this.state;

    const arrs = {
      1: [6, 7, 8, 9],
      2: [78, 79, 19, 20, 97, 98, 34],
      3: [185, 186, 176, 177],
      4: [265, 266, 208, 209],
      5: [360, 361, 362, 386, 387, 388, 389, 390, 391, 392, 353, 354, 355, 356, 357, 358],
    };
    let result = {
      1: false,
      2: false,
      3: false,
      4: false,
      5: false,
    };
    let specialResult = {
      1: false,
      2: false,
      3: false,
    };
    for (const key in njzd) {
      const computedArr = arrs[key];
      njzd[key].forEach(element => {
        console.log(element);
        for (let index = 0; index < computedArr.length; index++) {
          const computedArrItem = computedArr[index];
          if (computedArrItem == element) {
            result[key] = true;
            return;
          }
        }
      });
    }

    if (result[2]) {
      const specialCases = [[78, 79, 19, 20], [97, 98], [34]];
      njzd[2].forEach(item => {
        for (let index = 0; index < specialCases.length; index++) {
          const element = specialCases[index];
          element.forEach(elementArrItem => {
            if (elementArrItem == item) {
              specialResult[index + 1] = true;
              return;
            }
          });
        }
      });
    }

    return { result, specialResult };
  };

  initDetailData = () => {
    const { result, specialResult } = this.computedShowDetial();
    console.log(result, specialResult);
    let resetData = {
      swallowData: true,
      esophagusData: true,
      barrettData: true,
      refluxData: true,
      cardiaData: true,
      stomachData: true,
      duodenumData: true,
    };
    for (const key in result) {
      if (!result[key]) {
        console.log('result[key]', result[key], key);

        if (key == 1) {
          resetData.swallowData = false;
        } else if (key == 2) {
          for (const specialKey in specialResult) {
            if (specialKey == 1) {
              resetData.esophagusData = false;
            } else if (specialKey == 2) {
              resetData.barrettData = false;
            } else if (specialKey == 3) {
              resetData.refluxData = false;
            }
          }
        } else if (key == 3) {
          resetData.cardiaData = false;
        } else if (key == 4) {
          resetData.stomachData = false;
        } else if (key == 5) {
          resetData.duodenumData = false;
        }
      }
    }
    return resetData;
  };

  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { njzd } = this.state;
        let requsetData = [...njzd['1'], ...njzd['2'], ...njzd['3'], ...njzd['4'], ...njzd['5']];
        requsetData = requsetData.join(',');
        let njzd_content = this.state.njzd_content ? JSON.parse(this.state.njzd_content) : {};
        let resetData = this.initDetailData();

        console.log(resetData, 'resetData');
        for (const key in resetData) {
          if (!resetData[key]) {
            njzd_content[key] = [{}];
          }
        }
        njzd_content = JSON.stringify(njzd_content);

        this.setState(
          params => ({
            form: {
              ...params.form,
              id: this.props.record.id,
              njzd: requsetData,
              skip: '1',
              user: this.props.currentUser.id,
              njzd_content,
            },
          }),
          () => {
            this.updateRecord(this.state.form);
            this.setState({
              visible: false,
            });
          },
        );
      }
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  handleNjTabChange = key => {
    console.log(key);
    this.setState({ activeKey: key });
  };

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };
  handleBlUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;

      this.setState(params => ({
        form: {
          ...params.form,
          reportFilePath: filePath,
          reportFileUrl: url,
        },
        isUploading: false,
      }));
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };
  handleDelBlImage = () => {
    this.setState(params => ({
      form: {
        ...params.form,
        reportFilePath: '',
        reportFileUrl: '',
      },
    }));
  };

  nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        name: value,
      },
    }));
  };
  sfzChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sfz: value,
      },
    }));
  };

  screeningIdChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningId: value,
      },
    }));
  };

  phoneChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        phone: value,
      },
    }));
  };
  njNumChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        njNum: value,
      },
    }));
  };

  acheChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        ache: value,
      },
    }));
  };

  dyeChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        dye: value,
      },
    }));
  };
  isHjChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        isHj: value,
      },
    }));
  };

  njzlTimeChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        njzlTime: dateString,
      },
    }));
  };
  // hp选择切换触发
  hpChange = value => {
    this.setState(params => {
      let hpjcjgDisabled = false;
      if (value == 0) {
        params.form.hpjcjg = '';
        hpjcjgDisabled = true;
      } else hpjcjgDisabled = false;
      return {
        form: {
          ...params.form,
          hp: value,
        },
        hpjcjgDisabled,
      };
    });
  };

  hpjcjgChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        hpjcjg: value,
      },
    }));
  };

  picNumsChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        picNums: value,
      },
    }));
  };
  njStaffChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        njStaff: value,
      },
    }));
  };
  verifyStaffChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        verifyStaff: value,
      },
    }));
  };

  /**
   *
   * @param {*} options  tree结构中的选项
   * @returns
   */
  onCheckHandle = options => {
    return (checkedkeys, e) => {
      let { njzd, activeKey, showTags, treeListData } = this.state;
      njzd[activeKey] = checkedkeys;

      console.log(checkedkeys);
      // 当前点击选择的选项
      const current = checkedkeys[checkedkeys.length - 1];

      // 每个树下面的排他项的值
      const repelOptionValue = options[0].props.children[0].key;
      const repelOption = options[0].props.children[0];
      console.log(repelOption);
      if (checkedkeys.indexOf(repelOptionValue) >= 0) {
        njzd[activeKey] = [repelOptionValue];
      }
      showTags = this.getAllSelectTag();

      this.setState({
        njzd,
        showTags,
      });
    };
  };

  // 获取所有选择的病状
  getAllSelectTag() {
    const { njzd, treeListData } = this.state;
    let showTags = [];
    for (const key in njzd) {
      const item = njzd[key];
      for (let index = 0; index < item.length; index++) {
        const element = item[index];
        treeListData.forEach(el => {
          if (el.value === element) {
            showTags.push(el.title);
          }
        });
      }
    }
    return showTags;
  }

  //字典
  findAllDictName = () => {
    this.execHttp('treatmentList/findAllDictName').then(resp => {
      if (resp && resp.success) {
        const acheData = resp.data.ache.map(({ dictValue, dictName }) => {
          return { value: dictValue, label: dictName };
        });
        const isHjData = resp.data.is_hj.map(({ dictValue, dictName }) => {
          return { value: dictValue, label: dictName };
        });
        // 将树形结构保存为数组结构
        const treeListData = [
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag1))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag2))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag3))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag4))),
          ...this.treeToList(JSON.parse(JSON.stringify(resp.data.tag5))),
        ];
        this.setState(
          {
            tag1: resp.data.tag1,
            tag2: resp.data.tag2,
            tag3: resp.data.tag3,
            tag4: resp.data.tag4,
            tag5: resp.data.tag5,
            acheData: acheData,
            dyeData: resp.data.dye,
            hpData: resp.data.Hp,
            isHjData: isHjData,
            hpjcjgData: resp.data.hpjcjg,
            treeListData,
          },

          () => {
            this.findById();
          }
        );
      }
    });
  };

  //保存
  updateRecord = from => {
    this.execHttp('crowdDataReport/updateRecord', {
      ...from,
    }).then(resp => {
      if (resp && resp.success) {
        message.success(resp.message);
        this.props.getDataByPage();
      } else {
        message.error(resp.message);
      }
    });
  };

  /**详情*/
  findById = () => {
    this.execHttp('crowdDataReport/findById', {
      id: this.props.record.id,
    }).then(resp => {
      if (resp && resp.success) {
        if (resp.data.response.njzd) {
          const { njzd, tag1, tag2, tag3, tag4, tag5 } = this.state;
          let requestData = resp.data.response.njzd.split(',');
          // 数组去重   处理脏数据
          requestData = new Set(requestData);
          requestData = Array.from(requestData);

          const tem = [[...tag1], [...tag2], [...tag3], [...tag4], [...tag5]];
          requestData.forEach(element => {
            tem.forEach((elementData, index) => {
              if (this.recursion(element, elementData)) {
                njzd[index + 1].push(element);
              }
            });
          });

          this.setState(
            {
              njzd,
              njzd_content: resp.data.njzdDetail != null ? resp.data.njzdDetail.njzdContent : null,
            },
            () => {
              const showTags = this.getAllSelectTag();
              this.setState({
                showTags,
              });
            }
          );
        }
        this.setState({
          form: resp.data.response,
          getByIdOver: true,
        });
      }
    });
  };

  recursion = (element, elementData) => {
    let found = false;
    elementData.forEach(tar => {
      if (element == tar.id) {
        found = tar;
      } else {
        if (tar.children && tar.children.length > 0) {
          const childFound = this.recursion(element, tar.children);
          if (childFound) {
            found = tar;
            return;
          }
        }
      }
    });
    return found;
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

  treeToList = data => {
    let res = [];
    const dfs = tree => {
      tree.forEach(item => {
        if (item.children) {
          dfs(item.children);
          delete item.children;
        }
        res.push(item);
      });
    };
    dfs(data);

    return res;
  };

  // 从EndoscopetDetailTable获取内径详情信息
  getDetailInfo = value => {
    this.setState({
      njzd_content: JSON.stringify(value),
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible, tag1, tag2, tag3, tag4, tag5, njzd, activeKey, showTags } = this.state;

    // console.log(njzd);
    const ceshi = [2];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    let treeOptions = [
      this.renderTreeNodes(tag1),
      this.renderTreeNodes(tag2),
      this.renderTreeNodes(tag3),
      this.renderTreeNodes(tag4),
      this.renderTreeNodes(tag5),
    ];

    const { record } = this.props;
    const color = record.report_file_url ? '#67c23a' : '#e6a23c';
    return (
      <div style={{ display: 'inline-block' }}>
        <Button
          type="primary"
          style={{ marginLeft: '10px', background: color, borderColor: color }}
          onClick={this.showModal}
        >
          内镜
        </Button>
        <Modal
          title="内镜检查"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={1500}
        >
          <Form {...formItemLayout}>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="姓名">
                  <Input
                    placeholder="姓名"
                    value={this.state.form.name}
                    disabled
                    onChange={this.nameChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="身份证">
                  <Input
                    placeholder="身份证号码"
                    value={this.state.form.sfz}
                    disabled
                    onChange={this.sfzChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="调查对象ID号">
                  <Input
                    placeholder="调查对象ID号"
                    value={this.state.form.screeningId}
                    disabled
                    onChange={this.screeningIdChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="电话">
                  <Input
                    placeholder="电话"
                    value={this.state.form.phone}
                    disabled
                    onChange={this.phoneChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜号">
                  {getFieldDecorator('njNum', {
                    initialValue: this.state.form.njNum,
                    rules: [{ required: true, message: '内镜号不能为空' }],
                  })(
                    <Input
                      placeholder="内镜号"
                      onChange={this.njNumChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="是否无痛">
                  <Radio.Group
                    value={this.state.form.ache}
                    options={this.state.acheData}
                    onChange={this.acheChange}
                    style={{ width: 750 }}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="染色类型">
                  {getFieldDecorator('dye', {
                    initialValue: this.state.form.dye,
                    rules: [{ required: true, message: '染色类型不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.dyeChange}
                      style={{ width: 200 }}
                      placeholder="请选择染色类型"
                    >
                      {this.state.dyeData.map(item => (
                        <Select.Option key={item.dictValue}>{item.dictName}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="是否活检">
                  {getFieldDecorator('isHj', {
                    initialValue: this.state.form.isHj,
                    rules: [{ required: true, message: '活检不能为空' }],
                  })(
                    <Radio.Group
                      options={this.state.isHjData}
                      onChange={this.isHjChange}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜诊疗日期">
                  {getFieldDecorator('njzlTime', {
                    initialValue: this.state.form.njzlTime === null ? null : moment(this.state.form.njzlTime, 'YYYY-MM-DD'),
                    rules: [{ required: true, message: '内镜诊疗日期不能为空' }],
                  })(
                    <DatePicker
                      style={{ width: 200 }}
                      showTime
                      format="YYYY-MM-DD"
                      onChange={this.njzlTimeChange}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="hp">
                  {getFieldDecorator('hp', {
                    initialValue: this.state.form.hp,
                    rules: [{ required: true, message: 'hp检测不能为空' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.hpChange}
                      style={{ width: 200 }}
                      placeholder="请选择hp检测结果"
                    >
                      {this.state.hpData.map(item => (
                        <Select.Option key={item.dictValue}>{item.dictName}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="Hp检测方法">
                  {getFieldDecorator('hpjcjg', {
                    initialValue: this.state.form.hpjcjg,
                    rules: [{ required: this.state.form.hp !== '0', message: 'hp检测方法不能为空' }],
                  })(
                    <Select
                      allowClear
                      disabled={this.state.hpjcjgDisabled}
                      onChange={this.hpjcjgChange}
                      style={{ width: 200 }}
                      placeholder="请选择hp检测方法"
                    >
                      {this.state.hpjcjgData.map(item => (
                        <Select.Option key={item.dictValue}>{item.dictName}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="图片数量">
                  {getFieldDecorator('picNums', {
                    initialValue: this.state.form.picNums,
                    rules: [{ required: true, message: '图片数量不能为空' }],
                  })(
                    <Input
                      placeholder="图片数量"
                      onChange={this.picNumsChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="内镜诊断医师">
                  {getFieldDecorator('njStaff', {
                    initialValue: this.state.form.njStaff,
                    rules: [{ required: true, message: '内镜诊断医师不能为空' }],
                  })(
                    <Input
                      placeholder="内镜诊断医师"
                      onChange={this.njStaffChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="内镜审核医师">
                  {getFieldDecorator('verifyStaff', {
                    initialValue: this.state.form.verifyStaff,
                    rules: [{ required: true, message: '内镜审核医师不能为空' }],
                  })(
                    <Input
                      placeholder="内镜审核医师"
                      onChange={this.verifyStaffChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="内镜诊断">
                  <div
                    style={{ display: 'flex', marginLeft: '48px', width: '100%', flexWrap: 'wrap' }}
                  >
                    {showTags.map((item, index) => {
                      return (
                        <Tag
                          color="#87d068"
                          key={index}
                          style={{ marginLeft: '5px', marginTop: '5px' }}
                        >
                          {item}
                        </Tag>
                      );
                    })}
                  </div>
                  <div style={{ display: 'flex' }}>
                    <Tabs
                      activeKey={this.state.activeKey}
                      tabPosition={'left'}
                      onChange={this.handleNjTabChange}
                    >
                      <TabPane tab={'下咽'} key={'1'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[0])}
                          checkedKeys={[...njzd['1']]}
                        >
                          {treeOptions[0]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'食管'} key={'2'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[1])}
                          checkedKeys={[...njzd['2']]}
                        >
                          {treeOptions[1]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'贲门'} key={'3'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[2])}
                          checkedKeys={[...njzd['3']]}
                        >
                          {treeOptions[2]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'胃'} key={'4'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[3])}
                          checkedKeys={[...njzd['4']]}
                        >
                          {treeOptions[3]}
                        </Tree>
                      </TabPane>
                      <TabPane tab={'十二指肠'} key={'5'}>
                        <Tree
                          checkable
                          onCheck={this.onCheckHandle(treeOptions[4])}
                          checkedKeys={[...njzd['5']]}
                        >
                          {treeOptions[4]}
                        </Tree>
                      </TabPane>
                    </Tabs>
                  </div>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item labelCol={{ span: 2, offset: 0 }} label="内镜报告单">
                  <ReportCard
                    imagePreview={true}
                    emptyMsg={'暂无内镜报告单,请上传内镜报告单'}
                    uploadBtnLabel={'上传内镜报告单'}
                    fileUrl={this.state.form.reportFileUrl}
                    isUploading={this.state.isUploading}
                    beforeUpload={this.handleUploadBefore}
                    onChange={this.handleBlUploadChange}
                    onDelClick={this.handleDelBlImage}
                  ></ReportCard>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          {this.state.getByIdOver ? (
            <EndoscopetDetailTable
              ref={this.endoscopetDetailTable}
              njzd={njzd}
              getDetailInfo={this.getDetailInfo}
              njzdContent={this.state.njzd_content}
            />
          ) : (
            ''
          )}
        </Modal>
      </div>
    );
  }
}
